<script setup lang="ts">
import { GetCodeAPI, LoginSmsAPI } from '@/apis/login'
import { usetokenStore } from '@/stores/token'
import type { LoginSmsAPIParams } from '@/types/login'
import { ref } from 'vue'

defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})
const form = ref<LoginSmsAPIParams>({
  mobile: '13230000100',
  code: '',
})
const rules = ref<UniHelper.UniFormsRules>({
  mobile: {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号码格式不正确' },
    ],
  },
})
const formRef = ref<UniHelper.UniForms>()
const getcode = async () => {
  if (!form.value.mobile) {
    return uni.showToast({
      title: '请输入手机号',
      icon: 'none',
    })
  }
  const res = await GetCodeAPI({
    mobile: form.value.mobile,
    type: 'login',
  })
  console.log('code', res.data.code)
}
const isAgree = ref(false)
const store = usetokenStore()
const LoginOn = async () => {
  await formRef.value?.validate()
  if (!isAgree.value) {
    return uni.showToast({ title: '请先阅读并同意用户协议及隐私协议', icon: 'none' })
  }
  const res = await LoginSmsAPI(form.value)
  console.log('res', res)
  store.setToken(res.data.token)
  uni.switchTab({
    url: '/pages/index/index',
  })
}
</script>

<template>
  <uni-forms class="login-form" ref="formRef" v-model="form" :rules="rules">
    <uni-forms-item name="name">
      <uni-easyinput
        :input-border="false"
        v-model="form.mobile"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <uni-forms-item name="name">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        v-model="form.code"
        placeholder="请输入验证码"
        placeholder-style="color: #C3C3C5"
      />
      <text class="text-button" @click="getcode">获取验证码</text>
    </uni-forms-item>

    <view class="agreement" @click="isAgree = !isAgree">
      <radio :checked="isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="LoginOn">登 录</button>
  </uni-forms>
</template>

<style lang="scss">
@import './styles.scss';
</style>
